import { useRef, useState } from 'react';
import {
  FooterToolbar,
  ProForm,
  ProFormText,
  ProFormSelect,
  ProFormDateTimePicker,
  ProFormItem,
  ProFormDependency,
} from '@ant-design/pro-components';
import { Button, message, Space, Upload } from 'antd';
import { history } from 'umi';
import { PageContainer } from '@ant-design/pro-components';
import { primeextendDetail, primeextendEdit } from '@/services/server';
import useDetailType from '@/hooks/useDetailType';
import StorageManager from '@/utils/StorageManager';
import { EnumDealType, EnumPrimeMemberType } from '@/utils/constant';
import type { UploadFile, UploadProps } from 'antd/es/upload/interface';
import type { ProFormInstance } from '@ant-design/pro-components';

interface IParams {
  type?: string;
  id?: string;
}

import styles from './style.less';

const defaultValues = {
  usercodeFilePath: '',
  primeMemberTypeId: '',
  dealType: 0,
  setDateTime: null,
  extandDays: '',
  placeCardActivityId: '',
  expiredStartTime: null,
  expiredEndTime: null,
  deleteCardsActivityIds: '',
  remark: '',
};

const SensitizeManageDetail: React.FC = () => {
  const { isAdd, isModify, params } = useDetailType<IParams>();
  const formRef = useRef<ProFormInstance>();
  const [activityDisabeld, setActivityDisabeld] = useState(false);
  const [fileList, setFileList] = useState<UploadFile[]>([]);
  const [loading, setLoading] = useState<boolean>(false);
  const [fileUrlBro, setFileUrlBro] = useState<string>();

  const eunmList: any = StorageManager.getLocalStorageSync('eunmList');
  const OptionsSiteTagList = eunmList?.OptionsSiteTagList || [];

  // 新增或者编辑  表单内容-初始化
  const getDetail = async () => {
    // 编辑
    if (params.id && isModify) {
      setActivityDisabeld(true);
      const { code, data } = await primeextendDetail({
        id: params.id,
      });
      if (code === 200 && data) {
        return {
          ...data,
        };
      }
    }
    // 新增直接过来的
    if (params.id && isAdd) {
      setActivityDisabeld(true);
      return { ...defaultValues, activityId: params.id };
    }
    return { ...defaultValues };
  };

  const goToList = () => {
    history.push('/tool/delay/List');
  };

  const restProForm = () => {
    formRef.current?.setFieldsValue({
      ...defaultValues,
      activityId: activityDisabeld ? params.id : '',
    });
  };

  const onValueChange = (value: any) => {
    console.log(value, 'onValueChange');
  };

  const onFinish = async (value: Partial<API.CodegroupEditInfo>) => {
    console.log('onFinish---value', isAdd, isModify, value);
    const param: Partial<API.PrimeextendListItem> = {
      ...value,
    };
    // 编辑
    if (isModify && params.id) {
      param.id = params.id;
    }
    const { data, code } = await primeextendEdit(param);
    if (code === 200) {
      message.success('保存成功');
      goToList();
    }
  };

  const beforeUploadCrop = (file: File) => {
    console.log('file==file', file);
    if (file.type !== 'text/plain') {
      message.error('文件类型错误');
      return false;
    }
    if (file.size === 0) {
      message.error('上传的文件内容不得为空');
      return false;
    }
    if (file.size > 10 * 1024) {
      message.error('文件大小不得大于10MB!');
      return false;
    }
    return true;
  };

  const onFileChange: UploadProps['onChange'] = ({ file, fileList: newFileList }) => {
    const { status, response } = file || {};
    setFileList(newFileList);
    if (status === 'removed') {
      setFileUrlBro('');
      formRef.current?.setFieldValue('usercodeFilePath', '');
      // formRef.current?.validateFields(); // 上传文件之后--检验
    }
    // 没有status，说明没有上传，是本地文件
    if (!status) {
      setFileList([...fileList]);
    }
    if (status === 'uploading') {
      setLoading(true);
    }
    if (status === 'done') {
      const { code, data } = response || {};
      if (code === '200' && data) {
        setFileUrlBro(data);
        formRef.current?.setFieldValue('usercodeFilePath', data);
        // formRef.current?.validateFields(); // 上传文件之后--检验
      }
      setLoading(false);
    }
    if (status === 'error') {
      setLoading(false);
      setFileList([...fileList]);
      message.error('上传失败');
    }
  };

  const formatEnum = (list: any) => {
    const arr: { value: number; label: any }[] = [];
    Object.keys(list).forEach((key) => {
      arr.push({
        value: Number(key),
        label: list[key],
      });
    });
    return arr;
  };

  return (
    <PageContainer>
      <div className={styles['detail-body']}>
        <>
          <ProForm<Partial<API.CodegroupListItem>>
            formRef={formRef}
            layout="horizontal"
            labelCol={{ span: 4 }}
            wrapperCol={{ span: 20 }}
            scrollToFirstError
            onValuesChange={onValueChange}
            onFinish={onFinish}
            //@ts-ignore
            request={getDetail}
            submitter={{
              searchConfig: {
                resetText: '返回',
              },
              render: (_, dom) => (
                <FooterToolbar
                  extra={
                    <div style={{ textAlign: 'center', padding: '5px 0' }}>
                      <Space>
                        <Button type="primary" onClick={restProForm}>
                          重置
                        </Button>
                        <Button onClick={goToList}>返回</Button>
                        {dom[1]}
                      </Space>
                    </div>
                  }
                />
              ),
            }}
          >
            <>
              <ProForm.Group>
                <ProFormText
                  labelCol={{ span: 8 }}
                  width="lg"
                  name="usercodeFilePath"
                  label="任务文件"
                  placeholder="请上传文件"
                  disabled
                  rules={[{ required: true, message: '不得为空' }]}
                />
                <ProFormItem label={null} labelCol={{ span: 8 }}>
                  <Upload
                    name="file"
                    accept=".txt"
                    listType={'text'}
                    headers={{
                      ticket: `${StorageManager.getLocalStorageSync('token')}`,
                      contentType: 'multipart/form-data',
                    }}
                    fileList={fileList}
                    action={`${API_CONFIGS.server}${API_CONFIGS.prefix}/primeextend/upload`}
                    beforeUpload={beforeUploadCrop}
                    onChange={onFileChange}
                  >
                    {fileList.length === 0 && (
                      <Button type="primary" loading={loading}>
                        点击上传
                      </Button>
                    )}
                  </Upload>
                </ProFormItem>
                <ProFormSelect
                  labelCol={{ span: 8 }}
                  width="lg"
                  name="primeMemberTypeId"
                  label="身份类型"
                  placeholder="primeMemberTypeId"
                  rules={[{ required: true, message: '不得为空' }]}
                  options={EnumPrimeMemberType}
                />
                <ProFormSelect
                  labelCol={{ span: 8 }}
                  width="lg"
                  name="dealType"
                  label="处理类型 "
                  placeholder="dealType"
                  options={formatEnum(EnumDealType)}
                  fieldProps={{
                    dropdownMatchSelectWidth: 400,
                    dropdownStyle: {
                      width: 400,
                    },
                    width: '400',
                    onChange: (e) => {
                      formRef.current?.validateFields();
                    },
                  }}
                  rules={[{ required: true, message: '不得为空' }]}
                />
                <ProFormDependency name={['dealType']}>
                  {({ dealType }) => {
                    return (
                      <>
                        <ProFormDateTimePicker
                          labelCol={{ span: 8 }}
                          width="lg"
                          name="setDateTime"
                          label="设置效期时间"
                          fieldProps={{
                            placeholder: 'setDateTime',
                            format: 'YYYY-MM-DD HH:mm:ss',
                          }}
                          rules={[{ required: [0, 20].includes(dealType), message: '不得为空' }]}
                        />
                      </>
                    );
                  }}
                </ProFormDependency>
                <ProFormDependency name={['dealType']}>
                  {({ dealType }) => {
                    return (
                      <>
                        <ProFormText
                          labelCol={{ span: 8 }}
                          width="lg"
                          name="extandDays"
                          label="延期天数"
                          placeholder="extandDays"
                          rules={[
                            { required: [1, 3, 11, 23].includes(dealType), message: '不得为空' },
                          ]}
                        />
                      </>
                    );
                  }}
                </ProFormDependency>
                <ProFormDependency name={['dealType']}>
                  {({ dealType }) => {
                    return (
                      <>
                        <ProFormText
                          labelCol={{ span: 8 }}
                          width="lg"
                          name="placeCardActivityId"
                          label={
                            dealType === 24
                              ? '升级的卡'
                              : dealType === 5
                              ? 'primeOfferId'
                              : '卡activityId'
                          }
                          placeholder="placeCardActivityId"
                          rules={[{ required: [2, 5, 24].includes(dealType), message: '不得为空' }]}
                        />
                      </>
                    );
                  }}
                </ProFormDependency>
                <ProFormDependency name={['dealType']}>
                  {({ dealType }) => {
                    return (
                      <>
                        <ProFormDateTimePicker
                          labelCol={{ span: 8 }}
                          width="lg"
                          name="expiredStartTime"
                          label="身份过期时间范围开始时间"
                          fieldProps={{
                            placeholder: 'expiredStartTime',
                            format: 'YYYY-MM-DD HH:mm:ss',
                          }}
                          rules={[
                            {
                              required: [0, 1, 3, 11, 20, 24, 23].includes(dealType),
                              message: '不得为空',
                            },
                          ]}
                        />
                      </>
                    );
                  }}
                </ProFormDependency>
                <ProFormDependency name={['dealType']}>
                  {({ dealType }) => {
                    return (
                      <>
                        <ProFormDateTimePicker
                          labelCol={{ span: 8 }}
                          width="lg"
                          name="expiredEndTime"
                          label="身份过期时间范围结束时间"
                          fieldProps={{
                            placeholder: 'expiredEndTimes',
                            format: 'YYYY-MM-DD HH:mm:ss',
                          }}
                          rules={[
                            {
                              required: [0, 1, 3, 11, 20, 24, 23].includes(dealType),
                              message: '不得为空',
                            },
                          ]}
                        />
                      </>
                    );
                  }}
                </ProFormDependency>

                <ProFormDependency name={['dealType']}>
                  {({ dealType }) => {
                    return (
                      <>
                        <ProFormText
                          labelCol={{ span: 8 }}
                          width="lg"
                          name="deleteCardsActivityIds"
                          label="删除多出来的卡"
                          placeholder="deleteCardsActivityIds"
                          rules={[
                            {
                              required: [12].includes(dealType),
                              message: '不得为空',
                            },
                          ]}
                        />
                      </>
                    );
                  }}
                </ProFormDependency>
                <ProFormText
                  labelCol={{ span: 8 }}
                  width="lg"
                  name="remark"
                  label="备注"
                  placeholder="remark"
                />
              </ProForm.Group>
            </>
          </ProForm>
        </>
      </div>
    </PageContainer>
  );
};

export default SensitizeManageDetail;
